package com.example.demos.web.controller;

import com.example.demos.dto.SupplierDTO;
import com.example.demos.entity.Supplier;
import com.example.demos.service.SupplierService;
import com.example.demos.util.*;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigInteger;
import java.util.List;
@Slf4j
@RequestMapping("/v2/supplier")
@RestController
public class SupplierController {
    @Autowired
    private SupplierService supplierService;

    @GetMapping("/listByPage")
    Result<PageBean<List<Supplier>>> listByPage(HttpServletResponse response,@RequestParam("t1.type") Integer type ,SupplierDTO supplierDTO) {
        supplierDTO.setType(type.toString());
        if (type == 1 || type == 2) {
            return Result.ok(supplierService.selectSupplierListByPage(supplierDTO));
        }
        response.setStatus(404);
        return Result.error();
    }
    @PostMapping("/add")
    Result<Void> add(HttpServletResponse response,@RequestParam("t.type") Integer type ,Supplier supplier){

            if(supplier.getName()==null||supplier.getEmail()==null||supplier.getAddress()==null||supplier.getContact()==null||supplier.getTelephone()==null ){
                return Result.bizErr("您输入的字段有空的属性，请重新输入。");
            }
        supplier.setType(type.toString());
        if(type==1 || type==2) {
            if (supplierService.selectExist(supplier))
            {
                if (supplierService.addSupplier(supplier)){
                    return Result.ok("添加成功");
                }else {
                    return Result.bizErr("邮箱或手机传入有误，添加失败");
                }
            }else {
                return Result.bizErr("数据重复，添加失败");
            }
        }
        response.setStatus(404);
        return Result.error();
    }
    @DeleteMapping()
    Result<Void>delete(BigInteger id){
        supplierService.deleteSupplier(id);
        return Result.ok("删除成功");
    }
    @GetMapping("/selectone")
    Result<Supplier> selectOne(BigInteger id){
       return Result.ok(supplierService.selectSupplierById(id));
    }
    @PostMapping("/update")
    Result<Void> updateSupplier(HttpServletResponse response,Supplier supplier){
        if(supplierService.updateSupplier(supplier)){
            return Result.ok("修改成功");
        }
        response.setStatus(400);
        return Result.bizErr("邮箱或手机传入有误，添加失败");
    }
}

